package com.likeycy.my.set;

import com.likeycy.my.list.List;
import com.likeycy.my.list.MyLinkedList;

/**
 * @ClassName: MyListSet
 * @Description: 实现MyListSet集合
 * @Author: sodagreen
 * @Date: 2021/3/24 23:22
 * @Version: 1.0
 */
public class MyListSet<E> implements MySet<E> {

    private List<E> list = new MyLinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E element) {
        return list.contains(element);
    }

    @Override
    public void add(E element) {
        if (element == null) {
            throw new NullPointerException();
        }

        /*if (list.contains(element)) {
            return;
        }
        list.add(element);*/
        int index = list.indexOf(element);
        if (index != List.ELEMENT_NOT_FOUND) {
            list.set(index, element);
        } else {
            list.add(element);
        }
    }

    @Override
    public void remove(E element) {
        if (element == null) {
            throw new NullPointerException();
        }
        int index = list.indexOf(element);
        if (index != List.ELEMENT_NOT_FOUND) {
            list.remove(index);
        }
    }

    @Override
    public void traversal(Visitor<E> visitor) {
        if (visitor == null) {
            return;
        }
        int size = list.size();
        for (int i = 0; i < size; i++) {
            if (visitor.visit(list.get(i))) {
                return;
            }
        }
    }
}
